package com.cnki.caselib.business.impl;

import java.util.List;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;

import com.cnki.caselib.business.UserManager;
import com.cnki.caselib.dao.UserDao;
import com.cnki.caselib.domain.LoginSession;
import com.cnki.caselib.domain.User;
import com.cnki.caselib.exception.LoginFailedException;
import com.cnki.caselib.exception.UserNotFoundException;

public class UserManagerImpl implements UserManager {
	private UserDao userDao;

	public LoginSession login(String username, String password, int type)
			throws LoginFailedException {
		if (StringUtils.isEmpty(password)) {
			throw new LoginFailedException("Empty password is not allowed");
		}
		final User user = userDao.getUserByUsername(username);
		if (user == null) {
			throw new LoginFailedException("User " + username
					+ " does not exist.");
		}
		if (type == 0 && user.getCredit() == 2) {
			throw new LoginFailedException("User: "+user.getUsername()+"  have no event authority!");
		}
		if(type == 1 && user.getCredit() == 1){
			throw new LoginFailedException("User: "+user.getUsername()+"  have no case authority!");
		}
		if (DigestUtils.md5Hex(password).equals(user.getPassword())) {
			return new LoginSession() {
				public int getAccountStatus() {
					return 0;
				}

				public int getPermission() {
					return 0;
				}

				public User getUser() {
					return user;
				}
			};
		} else {
			throw new LoginFailedException(
					"Username and password does not match.");
		}

	}

	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}

	public User getUserByUsername(String username) throws UserNotFoundException {
		User user = userDao.getUserByUsername(username);
		if (user == null) {
			throw new UserNotFoundException("user not found for username "
					+ username);
		}
		return user;
	}

	public boolean changePasswd(User user, String oldpassword,
			String newpassword) throws LoginFailedException {
		if (oldpassword.equals(user.getPassword())) {
			throw new LoginFailedException("User password is not correct.");
		}
		user.setPassword(DigestUtils.md5Hex(newpassword));
		if (userDao.update(user) == 1)
			return true;
		return false;
	}

	public boolean addUser(User user) {
		user.setPassword(DigestUtils.md5Hex(user.getPassword()));
		Long ret = (Long) userDao.insert(user);
		if (ret == 0)
			return false;
		return true;
	}

	public List<User> getAllUsers() {
		return userDao.getAllUsers();
	}

}
